#!/usr/bin/env python
# load.py  -  Loads a dictionary lookup-file into memory, ready to aid in translation lookups
# Tim Kane (385199
#
# 19 March 2010


from __future__ import division
import nltk, re, pprint, os



def load(filename):
	'''
	loads the specified file (or default filename if a directory is specified)
	The default filename in this instance is 'enfr.dict'
	'''


	if (os.path.isdir(filename)):
		filename = filename + "/enfr.dict"

	if (os.path.isfile(filename)):
		infile = open(filename,"r")
	else:
		print ("invalid path/file: %s" % filename)
		exit(-1)

	dictionary = dict()

	while infile:
        	line = infile.readline()
		if (line == ""):   # EOF reached
			break;

		line = line.rstrip()

        	translation=re.split('\t', line)

		# Our file format specifies that for each line, the first word denotes the English source word
		# and the all subsequent words on that line denote the foreign target word

		english=translation.pop(0)
		dictionary[english]=translation

	infile.close();

	return dictionary


if __name__ == "__main__":
	'''
	Write Python code to populate a dictionary, mapping English words to
	sets of French words.  Define a function load(), which takes the input
	filename (or directory name).  Put this in a file load.py, in the same
	directory as the data

	Provide test code which is run when the program is called on the command
	line (using: if __name__ == '__main__').  It should load the data and
	iterate over it, in sorted order, by English keys, printing lines of the
	form: english_word: french_word1; french_word2; ...
	'''


	dict = load ("./");

	# Note: There is no decent exception handling on this.  


	# We want to write out the entire vocabulary, in sorted order of English source words.

	# We can't sort a dictionary structure, but if we create a list containing just the key values	
	# we can use it as a sorted index to the dictionary.

	dict_list = list (dict)
	dict_list.sort()
	for key in dict_list:
		keyvalstr = key + ": "

		for val in dict[key]:
			keyvalstr = keyvalstr + " " + val + ";"

		print keyvalstr

	
	# I am assuming that it is acceptable to have a trailing ';' on the final element of a definition

	exit(0)
